// API配置
const API_CONFIG = {
  READ_API: '/api',  // 使用相对路径，通过Vite代理转发
  WRITE_API: '/api'  // 使用相对路径，通过Vite代理转发
};

// 响应数据接口 - 根据Swagger文档调整
interface ApiResponse<T = any> {
  code: number;
  msg: string;  // 改为msg，与后端一致
  data: T;
}

// 登录请求接口
interface LoginRequest {
  username: string;
  password: string;
}

// 登录响应接口 - 根据Swagger文档调整
interface LoginResponse {
  id: number;
  username: string;
  password: string | null;
  email: string;
  phone: string | null;
  realName: string;
  role: number;
  isActive: boolean | null;
  isLocked: boolean | null;
  lastLoginTime: string;
  lastloginIp: string;
  createdAt: string | null;
  updatedAt: string | null;
}

// 请求配置
const requestConfig = {
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization'
  },
  withCredentials: false  // 跨域请求不发送cookies
};

// 创建axios实例
import axios from 'axios';

// 创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 10000,
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 用户相关API
export const user = {
  login: (data: { username: string; password: string }) => 
    request.post('/User/login', data),
  getProfile: () => request.get('/User/profile'),
}

// 供应商相关API
export const supplier = {
  getList: (params: SupplierSearchParams) => 
    request.get<ApiResult<ApiPaging<Supplier>>>('/Supplier/list', { params }),
  getById: (id: number) => 
    request.get<ApiResult<Supplier>>(`/Supplier/${id}`),
  create: (data: any) => 
    request.post('/Supplier/add', data),
  update: (id: number, data: any) => 
    request.put(`/Supplier/update/${id}`, data),
  delete: (id: number) => 
    request.delete(`/Supplier/delete/${id}`),
  search: (keyword: string, pageIndex = 1, pageSize = 10) => 
    request.get<ApiResult<ApiPaging<Supplier>>>('/Supplier/search', { 
      params: { keyword, pageIndex, pageSize } 
    }),
  getStatistics: () => 
    request.get<ApiResult<SupplierStatistics>>('/Supplier/statistics'),
  initTestData: () => 
    request.post<ApiResult<string>>('/Supplier/init-test-data'),
}

// 客户相关API
export const customer = {
  getList: (params: any) => 
    request.get<ApiResult<ApiPaging<any>>>('/Customer/list', { params }),
  getById: (id: number) => 
    request.get<ApiResult<any>>(`/Customer/${id}`),
  create: (data: any) => 
    request.post('/Customer/add', data),
  update: (id: number, data: any) => 
    request.put(`/Customer/update/${id}`, data),
  delete: (id: number) => 
    request.delete(`/Customer/delete/${id}`),
  search: (keyword: string, pageIndex = 1, pageSize = 10) => 
    request.get<ApiResult<ApiPaging<any>>>('/Customer/search', { 
      params: { keyword, pageIndex, pageSize } 
    }),
  getStatistics: () => 
    request.get<ApiResult<any>>('/Customer/statistics'),
  initTestData: () => 
    request.post<ApiResult<string>>('/Customer/init-test-data'),
}

// 羊只相关API
export const sheep = {
  getInventoryStatistics: (params?: any) => 
    request.get<ApiResult<any>>('/Sheep/inventory-statistics', { params }),
  getRealTimeInventory: (params?: any) => 
    request.get<ApiResult<any>>('/Sheep/real-time-inventory', { params }),
  getInventoryTrend: (params?: any) => 
    request.get<ApiResult<any>>('/Sheep/inventory-trend', { params }),
  getRealTimeMonitoring: (params?: any) => 
    request.get<ApiResult<any>>('/Sheep/real-time-monitoring', { params }),
  getLambingStatistics: (params?: any) => 
    request.get<ApiResult<any>>('/Sheep/lambing-statistics', { params }),
  getLambingMonitoring: (params?: any) => 
    request.get<ApiResult<any>>('/Sheep/lambing-monitoring', { params }),
  getBreedingStatistics: (params?: any) => 
    request.get<ApiResult<any>>('/Sheep/breeding-statistics', { params }),
  getBreedingMonitoring: (params?: any) => 
    request.get<ApiResult<any>>('/Sheep/breeding-monitoring', { params }),
  getProductionStatistics: (params?: any) => 
    request.get<ApiResult<any>>('/Sheep/production-statistics', { params }),
  getProductionMonitoring: (params?: any) => 
    request.get<ApiResult<any>>('/Sheep/production-monitoring', { params }),
  getFarms: () => 
    request.get<ApiResult<any>>('/Sheep/farms'),
  getDatabaseStatus: () => 
    request.get<ApiResult<any>>('/Sheep/database-status'),
  seedData: () => 
    request.get<ApiResult<any>>('/Sheep/seed-data'),
  // 导出相关API
  exportInventoryStatistics: (params?: any) => 
    request.get('/Sheep/inventory-statistics/export', { 
      params,
      responseType: 'blob' // 重要：设置响应类型为blob以处理文件下载
    }),
}



// 接口定义
export interface SupplierSearchParams {
  pageIndex: number
  pageSize: number
  supplierCode?: string
  supplierName?: string
  contactPerson?: string
  contactPhone?: string
  supplierType?: string
  isActive?: boolean
  industry?: string
  mnemonicCode?: string
  sortBy?: string
  sortOrder?: string
}

export interface Supplier {
  id?: number
  supplierCode?: string
  supplierName?: string
  contactPerson?: string
  contactPhone?: string
  contactIdNumber?: string
  address?: string
  industry?: string
  creditCode?: string
  memo?: string
  supplierType?: string
  mnemonicCode?: string
  servicePersonnel?: string
  salesperson?: string
  supplierAttributes?: string
  belongsToUnit?: string
  market?: string
  isActive?: boolean
  createdAt?: string
  updatedAt?: string
}



export interface ApiPaging<T> {
  data: T[]
  totalCount: number
  pageIndex: number
  pageSize: number
  totalPages: number
}

export interface ApiResult<T> {
  code: number
  msg: string
  data: T
}

export interface SupplierStatistics {
  totalCount: number
  activeCount: number
  inactiveCount: number
  typeStatistics: Record<string, number>
  topIndustries: Record<string, number>
}



export { request }
export const api = { user, supplier, customer, sheep }
